package com.controller;

import com.bean.User;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author cyf
 * @description
 * @create 2018-09-10 16:21
 **/
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/")
    public String loginPage() {
        return "login";
    }

    @RequestMapping(value = "/result")
    public ModelAndView loginCheck(HttpServletRequest request, LoginCommand loginCommand) {
        
        boolean isValidUser = userService.getMatchCount(loginCommand.getUserName(), loginCommand.getPassWord());

        if (!isValidUser) {
            return new ModelAndView("login", "error", "用户名密码错误");
        } else {

            User user = userService.getUserByUserName(loginCommand.getUserName());

            user.setLoginIp(request.getLocalAddr());
            user.setLoginDate(new Date());

            userService.loginSuccess(user);
            request.getSession().setAttribute("user", user);
            return new ModelAndView("main");
        }
    }


}
